#include "one_wire.h"
#include "c51.h"
#include "utils.h"

#define OneWireDQ P3_7

u8 one_wire_init(void) {
  OneWireDQ = 1;
  OneWireDQ = 0;
  delay_500us();
  OneWireDQ = 1;
  delay_70us();
  u8 bit = OneWireDQ;
  delay_500us();
  return bit;
}

void one_wire_write(u8 bit) {
  OneWireDQ = 0;
  delay_10us();
  OneWireDQ = bit;
  delay_50us();
  OneWireDQ = 1;
}

u8 one_wire_read(void) {
  OneWireDQ = 0;
  delay_5us();
  OneWireDQ = 1;
  delay_5us();
  u8 bit = OneWireDQ;
  delay_50us();
  return bit;
}

void one_wire_write_byte(u8 byte) {
  for (u8 i = 0; i < 8; ++i) {
    one_wire_write(byte & (1 << i));
  }
}

u8 one_wire_read_byte(void) {
  u8 byte = 0;
  for (u8 i = 0; i < 8; ++i) {
    if (one_wire_read()) {
      byte |= 1 << i;
    }
  }
  return byte;
}
